﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Globalization;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using Common;
using Model;

namespace AcceptServer.Service
{
    class TaxiProtocol
    {
        private static readonly Hashtable _taxiGpsHistoryInfoBufferList = Hashtable.Synchronized(new Hashtable());
        private static readonly Hashtable _imageDataBufferList = Hashtable.Synchronized(new Hashtable());
        OperateDataBase operateDataBase = new OperateDataBase();
        public void TaxiUpdataGpsInfo(byte[] realData, IPAddress clientIp)
        {

            TaxiGpsHistoryInfo taxiGpsHistoryInfo = new TaxiGpsHistoryInfo();
            byte[] tempData = new byte[5];
            Array.Copy(realData, ConstParameters.MBodySatrtIndex, tempData, 0, 5);
            taxiGpsHistoryInfo.Longitude = double.Parse(CommonRoutine.ByteToBcdString(tempData)) / 1000000;
            Array.Copy(realData, ConstParameters.MBodySatrtIndex + 5, tempData, 0, 5);
            taxiGpsHistoryInfo.Latitude = double.Parse(CommonRoutine.ByteToBcdString(tempData)) / 1000000;
            taxiGpsHistoryInfo.Taxistate = realData[ConstParameters.MBodySatrtIndex + 10];
            taxiGpsHistoryInfo.AlarmL = realData[ConstParameters.MBodySatrtIndex + 11];
            taxiGpsHistoryInfo.DriverPhoneNumber = OperateAgreement.GetPhoneNumInMessageHead(realData);
            taxiGpsHistoryInfo.Time = DateTime.Now;


            #region

            TaxiInfo taxiInfo = new TaxiInfo
            {
                DriverPhoneNumber = taxiGpsHistoryInfo.DriverPhoneNumber,
                UpdateTime = taxiGpsHistoryInfo.Time,
                TaxiState = taxiGpsHistoryInfo.Taxistate,
                Latitude = taxiGpsHistoryInfo.Latitude,
                Longitude = taxiGpsHistoryInfo.Longitude,
                Ip = clientIp,
                AlarmL = taxiGpsHistoryInfo.AlarmL
            };

            try
            {

                AcceptMainForm.PositionService.UpdateTaxiInfo(taxiInfo);
                // lock (AcceptMainForm.TaxiGpsHistoryInfoQueue)

                {
                    AcceptMainForm.DataQueue.Enqueue(taxiGpsHistoryInfo);
                }
            }
            catch (Exception ex)
            {
                CommonRoutine.HandlingExceptions(ex);
                LogService.WriteLog("TaxiProtocol.cs-61");
            }

            #endregion

        }

        public void TaxiUpdataGpsInfo2(byte[] realData, IPAddress clientIp)
        {
             
            TaxiGpsHistoryInfo taxiGpsHistoryInfo = new TaxiGpsHistoryInfo();
            byte[] tempData = new byte[5];
            Array.Copy(realData, ConstParameters.MBodySatrtIndex, tempData, 0, 5);
            taxiGpsHistoryInfo.Longitude = double.Parse(CommonRoutine.ByteToBcdString(tempData)) / 1000000;
            Array.Copy(realData, ConstParameters.MBodySatrtIndex + 5, tempData, 0, 5);
            taxiGpsHistoryInfo.Latitude = double.Parse(CommonRoutine.ByteToBcdString(tempData)) / 1000000;
            taxiGpsHistoryInfo.Taxistate = realData[ConstParameters.MBodySatrtIndex + 10];
            taxiGpsHistoryInfo.AlarmL = realData[ConstParameters.MBodySatrtIndex + 11];
            taxiGpsHistoryInfo.DriverPhoneNumber = OperateAgreement.GetPhoneNumInMessageHead(realData);
            taxiGpsHistoryInfo.Time = DateTime.Now;
            short angle = BitConverter.ToInt16(realData, ConstParameters.MBodySatrtIndex + 12);
            byte speed = realData[ConstParameters.MBodySatrtIndex + 14];
            #region

            TaxiInfo taxiInfo = new TaxiInfo
            {
                DriverPhoneNumber = taxiGpsHistoryInfo.DriverPhoneNumber,
                UpdateTime = taxiGpsHistoryInfo.Time,
                TaxiState = taxiGpsHistoryInfo.Taxistate,
                Latitude = taxiGpsHistoryInfo.Latitude,
                Longitude = taxiGpsHistoryInfo.Longitude,
                Ip = clientIp,
                AlarmL = taxiGpsHistoryInfo.AlarmL,
                Angle = angle,
                Speed = speed
            };



            //----------------------
            //if (AcceptMainForm.RentCar_phoneNumbers.Contains(taxiInfo.DriverPhoneNumber))
            //{
            //    taxiInfo.isZhulin = true;
            //    AcceptMainForm.RentCarList[taxiInfo.DriverPhoneNumber] = taxiInfo;
            //    //return;
            //}


            try
            {

                AcceptMainForm.PositionService.UpdateTaxiInfo(taxiInfo);
                // lock (AcceptMainForm.TaxiGpsHistoryInfoQueue)

                {
                    AcceptMainForm.DataQueue.Enqueue(taxiGpsHistoryInfo);
                }
            }
            catch (Exception ex)
            {
                CommonRoutine.HandlingExceptions(ex);
                LogService.WriteLog("TaxiProtocol.cs-111");
            }

            #endregion

        }

        
        public void CarUpdataGpsInfoWithCarType(byte[] realData, IPAddress clientIp)
        {             
            TaxiGpsHistoryInfo taxiGpsHistoryInfo = new TaxiGpsHistoryInfo();
            byte[] tempData = new byte[5];
            Array.Copy(realData, ConstParameters.MBodySatrtIndex, tempData, 0, 5);
            taxiGpsHistoryInfo.Longitude = double.Parse(CommonRoutine.ByteToBcdString(tempData)) / 1000000;
            Array.Copy(realData, ConstParameters.MBodySatrtIndex + 5, tempData, 0, 5);
            taxiGpsHistoryInfo.Latitude = double.Parse(CommonRoutine.ByteToBcdString(tempData)) / 1000000;
            taxiGpsHistoryInfo.Taxistate = realData[ConstParameters.MBodySatrtIndex + 10];
            taxiGpsHistoryInfo.AlarmL = realData[ConstParameters.MBodySatrtIndex + 11];
            taxiGpsHistoryInfo.DriverPhoneNumber = OperateAgreement.GetPhoneNumInMessageHead(realData);
            taxiGpsHistoryInfo.Time = DateTime.Now;
            short angle = BitConverter.ToInt16(realData, ConstParameters.MBodySatrtIndex + 12);
            byte speed = realData[ConstParameters.MBodySatrtIndex + 14];
           
             
            #region

            TaxiInfo taxiInfo = new TaxiInfo
            {
                DriverPhoneNumber = taxiGpsHistoryInfo.DriverPhoneNumber,
                UpdateTime = taxiGpsHistoryInfo.Time,
                TaxiState = taxiGpsHistoryInfo.Taxistate,
                Latitude = taxiGpsHistoryInfo.Latitude,
                Longitude = taxiGpsHistoryInfo.Longitude,
                Ip = clientIp,
                AlarmL = taxiGpsHistoryInfo.AlarmL,
                Angle = angle,
                Speed = speed,
                CarType = ConstParameters.CarTypeOfAmbulance
            };
            if (realData.Length > 15)
            {
               taxiInfo.CarType = realData[ConstParameters.MBodySatrtIndex + 15];
            }

            try
            {

                AcceptMainForm.PositionService.UpdateTaxiInfo(taxiInfo);
                // lock (AcceptMainForm.TaxiGpsHistoryInfoQueue)

                {
                    AcceptMainForm.DataQueue.Enqueue(taxiGpsHistoryInfo);
                }
            }
            catch (Exception ex)
            {
                CommonRoutine.HandlingExceptions(ex);
                LogService.WriteLog("TaxiProtocol.cs-111");
            }

            #endregion

        }
          

        public byte[] TaxiUpdataImageGpsInfo(byte[] realData, IPAddress clientIp)
        {
            byte[] sendData = new byte[1];
            int packageIndex = OperateAgreement.GetPackageIndexInMessageHead(realData);
            int packageCount = OperateAgreement.GetPackageCountInMessageHead(realData);
            string phoneNumber = OperateAgreement.GetPhoneNumInMessageHead(realData);

            Console.WriteLine("packageIndex-" + packageIndex + ",packageCount-" + packageCount);
            if (packageIndex == 0)
            {
                TaxiGpsHistoryInfo taxiGpsHistoryInfoBuffer = new TaxiGpsHistoryInfo();

                byte[] tempData = new byte[5];
                Array.Copy(realData, ConstParameters.MBodySatrtIndex, tempData, 0, 5);
                taxiGpsHistoryInfoBuffer.Longitude = double.Parse(CommonRoutine.ByteToBcdString(tempData)) / 1000000;
                Array.Copy(realData, ConstParameters.MBodySatrtIndex + 5, tempData, 0, 5);
                taxiGpsHistoryInfoBuffer.Latitude = double.Parse(CommonRoutine.ByteToBcdString(tempData)) / 1000000;
                taxiGpsHistoryInfoBuffer.Taxistate = realData[ConstParameters.MBodySatrtIndex + 10];
                taxiGpsHistoryInfoBuffer.AlarmL = realData[ConstParameters.MBodySatrtIndex + 11];
                taxiGpsHistoryInfoBuffer.DriverPhoneNumber = phoneNumber;
                _taxiGpsHistoryInfoBufferList[phoneNumber] = taxiGpsHistoryInfoBuffer;

                _imageDataBufferList[phoneNumber] = new Dictionary<int, byte[]>();
            }
            else
            {

                Dictionary<int, byte[]> imageDataBuffer = _imageDataBufferList[phoneNumber] as Dictionary<int, byte[]> ??
                                                          new Dictionary<int, byte[]>();
                int imagedatalength = OperateAgreement.GetMessageLengthInMessageHead(realData);
                byte[] tempbytes = new byte[imagedatalength];
                Array.Copy(realData, ConstParameters.MBodySatrtIndex, tempbytes, 0, imagedatalength);
                if (imageDataBuffer.ContainsKey(packageIndex))
                {
                    imageDataBuffer.Remove(packageIndex);
                }
                imageDataBuffer.Add(packageIndex, tempbytes);

                _imageDataBufferList[phoneNumber] = imageDataBuffer;
                if (imageDataBuffer.Count == packageCount - 1)
                {
                    TaxiGpsHistoryInfo taxiGpsHistoryInfoBuffer = _taxiGpsHistoryInfoBufferList[phoneNumber] as TaxiGpsHistoryInfo;
                    if (taxiGpsHistoryInfoBuffer == null)
                    {
                        return sendData;
                    }



                    List<byte> templist = new List<byte>();
                    for (int i = 1; i < packageCount; i++)
                    {
                        templist.AddRange(imageDataBuffer[i]);
                    }
                    taxiGpsHistoryInfoBuffer.Image = templist.ToArray();
                    taxiGpsHistoryInfoBuffer.Time = DateTime.Now;


                    //------Clear Buffer
                    _taxiGpsHistoryInfoBufferList.Remove(phoneNumber);
                    imageDataBuffer.Clear();
                    _imageDataBufferList.Remove(phoneNumber);
                    #region

                    TaxiInfo taxiInfo = new TaxiInfo
                    {
                        DriverPhoneNumber = taxiGpsHistoryInfoBuffer.DriverPhoneNumber,
                        UpdateTime = taxiGpsHistoryInfoBuffer.Time,
                        TaxiState = taxiGpsHistoryInfoBuffer.Taxistate,
                        Latitude = taxiGpsHistoryInfoBuffer.Latitude,
                        Longitude = taxiGpsHistoryInfoBuffer.Longitude,
                        Ip = clientIp,
                        AlarmL = taxiGpsHistoryInfoBuffer.AlarmL
                    };

                    try
                    {
                        AcceptMainForm.PositionService.UpdateTaxiInfo(taxiInfo);
                        operateDataBase.AddTaxiGpsHistoryInfo(taxiGpsHistoryInfoBuffer);
                    }
                    catch (Exception ex)
                    {
                        CommonRoutine.HandlingExceptions(ex, false);
                        LogService.WriteLog("TaxiProtocol.cs-199");
                    }

                    #endregion
                }
            }
            sendData = GetUploadImageGpsInfo(packageIndex);
            return sendData;

        }

        public byte[] GetUploadImageGpsInfo(int packageIndex)
        {
            byte[] phonebytes = new byte[6];
            byte[] body = new[] { (byte)packageIndex };
            byte[] head = OperateAgreement.GetMessageHead(ConstParameters.CmdTaxiUpdataImageGpsInfoReply, false, false, body.Length, phonebytes, new byte[2], 0, 0);
            byte[] sendData = OperateAgreement.PackageSendData(head, body);
            return sendData;
        }

        public byte[] TaxiRegister(byte[] realData, IPAddress clientIp)
        {
            byte[] phoneNumberbyts = new byte[6];
            Array.Copy(realData, 5, phoneNumberbyts, 0, 6);
            byte[] serialNumber = new byte[2];
            Array.Copy(realData, 11, serialNumber, 0, 2);
            string driverPhoneNumber = OperateAgreement.GetPhoneNumInMessageHead(realData);
            bool isExist;
            try
            {
                isExist = AcceptMainForm.PositionService.TaxiRegister(driverPhoneNumber, clientIp);
            }
            catch (Exception ex)
            {
                isExist = false;
                CommonRoutine.HandlingExceptions(ex);
                LogService.WriteLog("TaxiProtocol.cs-236");
            }
            List<byte> body = new List<byte>();
            if (isExist)
            {
                try
                {
                    // string asServerip = AcceptMainForm.PositionService.GetFreeAcceptServerIp(AcceptMainForm.ServerWebIp);
                    string asServerip = "218.106.116.174";
                    IPAddress ip;
                    bool isIpstr = Regex.IsMatch(asServerip, @"^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$");
                    if (isIpstr)
                    {
                        ip = IPAddress.Parse(asServerip);
                    }
                    else
                    {
                        IPAddress[] ips = Dns.GetHostAddresses(asServerip);
                        ip = ips.Length > 0 ? ips[0] : clientIp;
                        LogService.WriteDebugLog("解析的" + asServerip + "IP:为" + ip.ToString(), DateTime.Now);
                        if (ips.Length == 0)
                        {
                            LogService.WriteDebugLog(asServerip + "解析域名失败。", DateTime.Now);
                        }
                    }


                    body.Add(1);

                    body.AddRange(ip.GetAddressBytes());
                    string phonestr = OperateConfig.GetCenterPhoneNumber();
                    byte[] phoneBcd = CommonRoutine.BcdStringToBytes(phonestr.PadLeft(12, '0'));
                    body.AddRange(phoneBcd);



                    //longitude 
                    string longitudestr = OperateConfig.GetOffSetLongitude();
                    byte[] longitudeBytes = CommonRoutine.BcdStringToBytes(longitudestr);
                    body.AddRange(longitudeBytes);
                    //latitude 
                    string latitudestr = OperateConfig.GetOffSetLatitude();
                    byte[] latitudeBytes = CommonRoutine.BcdStringToBytes(latitudestr);
                    body.AddRange(latitudeBytes);

                   // string version = OperateConfig.GetTaxiClientVersion();
                    string version = AcceptMainForm.TaxiClientVersion;
                    byte[] vBytes = Encoding.GetEncoding("GBK").GetBytes(version);
                    body.AddRange(vBytes);
                }
                catch (Exception ex)
                {
                    CommonRoutine.HandlingExceptions(ex);
                    LogService.WriteLog("TaxiProtocol.cs-286");
                    body.Clear();
                    body.Add(0);
                }

            }
            else
            {
                LogService.WriteDebugLog("数据库中找不到改" + driverPhoneNumber + isExist.ToString(), DateTime.Now);
                body.Add(0);
            }


            byte[] messageHead = OperateAgreement.GetMessageHead(ConstParameters.CmdTaxiRegisterReply, false, false, body.Count, phoneNumberbyts,
                                                serialNumber, 0, 0);
            byte[] tempData = OperateAgreement.PackageSendData(messageHead, body.ToArray());
            return tempData;
        }

        public byte[] TaxiRegister2(byte[] realData, IPAddress clientIp)
        {
            byte[] phoneNumberbyts = new byte[6];
            Array.Copy(realData, 5, phoneNumberbyts, 0, 6);

            byte[] serialNumber = new byte[2];
            Array.Copy(realData, 11, serialNumber, 0, 2);

            string driverPhoneNumber = OperateAgreement.GetPhoneNumInMessageHead(realData);
            //0-7  IMEI 8byte
            byte[] IMEI_bytes = new byte[8];
            Array.Copy(realData, ConstParameters.MBodySatrtIndex, IMEI_bytes, 0, 8);
            string IMEI = CommonRoutine.ByteToBcdString(IMEI_bytes);
            IMEI = IMEI.Remove(0, 1);

            //8-11  4byte  Version
            byte[] version_bytes = new byte[4];
            Array.Copy(realData, ConstParameters.MBodySatrtIndex + 8, version_bytes, 0, 4);
            Array.Reverse(version_bytes);
            int nowVersion = BitConverter.ToInt32(version_bytes, 0);


            List<byte> body = new List<byte>();
            try
            {
                string result = AcceptMainForm.PositionService.TaxiRegister2(driverPhoneNumber, clientIp, IMEI, nowVersion);

                if (result == "0" || result == "1" || result == "2")
                {
                    body.Clear();
                    body.Add(byte.Parse(result));
                }
                else
                {
                    #region  AnalysisIP

                    string strServerId = result.Substring(0, result.IndexOf('|'));
                    string serverid = strServerId.Replace("Serverid:", "");
                    
                    //string serverid = result.Replace("Serverid:", "");
                    
                    string serverUrl = "gqcl.cityofcar.com"; //数据库取
                    //longitude 
                    string longitudestr = OperateConfig.GetOffSetLongitude();   //在数据库中读出
                    //latitude 
                    string latitudestr = OperateConfig.GetOffSetLatitude();  //在数据库中读出

                    int svId = -1;
                    int.TryParse(serverid, out svId);
                    ServerConfigInfo serverConfig = operateDataBase.ServerConfigGetModelById(svId);
                    if (serverConfig != null)
                    {
                        serverUrl = serverConfig.DNSURL;
                        longitudestr = serverConfig.LongitudeOffset.ToString();
                        latitudestr = serverConfig.LatitudeOffset.ToString();
                    }


                    #endregion

                    byte[] serverUrlbytes = Encoding.GetEncoding("GBK").GetBytes(serverUrl);
                    body.Add((byte)serverUrlbytes.Length);
                    body.AddRange(serverUrlbytes);
                    string phonestr = OperateConfig.GetCenterPhoneNumber();
                    byte[] phoneBcd = CommonRoutine.BcdStringToBytes(phonestr.PadLeft(12, '0'));
                    body.AddRange(phoneBcd);

                    byte[] longitudeBytes = CommonRoutine.BcdStringToBytes(longitudestr); //new byte[5];               
                    body.AddRange(longitudeBytes);

                    byte[] latitudeBytes = CommonRoutine.BcdStringToBytes(latitudestr);//new byte[5];
                    body.AddRange(latitudeBytes);

                    //string version = OperateConfig.GetTaxiClientVersion();
                    string version = AcceptMainForm.TaxiClientVersion;
                    byte[] vBytes = Encoding.GetEncoding("GBK").GetBytes(version);
                    body.AddRange(vBytes);
                }

            }
            catch (Exception ex)
            {
                CommonRoutine.HandlingExceptions(ex);
                LogService.WriteLog("TaxiProtocol.cs-385");
                body.Clear();
                body.Add(0);
            }


            byte[] messageHead = OperateAgreement.GetMessageHead(ConstParameters.CmdTaxiRegisterReply2, false, false, body.Count, phoneNumberbyts,
                                                serialNumber, 0, 0);
            byte[] tempData = OperateAgreement.PackageSendData(messageHead, body.ToArray());
            return tempData;
        }


        //---------
        public byte[] TaxiRegister3(byte[] realData, IPAddress clientIp)
        {
            byte[] phoneNumberbyts = new byte[6];
            Array.Copy(realData, 5, phoneNumberbyts, 0, 6);

            byte[] serialNumber = new byte[2];
            Array.Copy(realData, 11, serialNumber, 0, 2);

            string driverPhoneNumber = OperateAgreement.GetPhoneNumInMessageHead(realData);
            //0-7  IMEI 8byte
            byte[] IMEI_bytes = new byte[8];
            Array.Copy(realData, ConstParameters.MBodySatrtIndex, IMEI_bytes, 0, 8);
            string IMEI = CommonRoutine.ByteToBcdString(IMEI_bytes);
            IMEI = IMEI.Remove(0, 1);

            //8-11  4byte  Version
            byte[] version_bytes = new byte[4];
            Array.Copy(realData, ConstParameters.MBodySatrtIndex + 8, version_bytes, 0, 4);
            Array.Reverse(version_bytes);
            int nowVersion = BitConverter.ToInt32(version_bytes, 0);

            string signature = "";

            List<byte> body = new List<byte>();
            try
            { 
                string result = AcceptMainForm.PositionService.TaxiRegister2(driverPhoneNumber, clientIp, IMEI, nowVersion);

                if ( result == "1" || result == "2")// 1.Imei验证失败 2.未能从数据库获取到该车信息
                {
                    body.Clear();
                    body.Add(byte.Parse(result));
                }
                else
                {
                    byte type = 0;
                    byte privateResult = 0;
                    string ss = string.Empty;
                    if (result == "0") // 该出租车号码数据库中不存在
                    {
                        string resultPrivate = AcceptMainForm.PositionService.PrivateCarRegister
                            (driverPhoneNumber, clientIp, IMEI, nowVersion);
                        if (resultPrivate[0]=='2')
                        {
                            // type = 3 表示是私家车
                            type = 3;
                            //"2|" + model.Signature;
                            signature = resultPrivate.Substring(
                                resultPrivate.IndexOf('|')+1);
                        }
                        else if (resultPrivate[0] == '0')
                        {
                            //表示私家车中也无此号
                            privateResult = 0;
                        }
                        else if (resultPrivate[0] == '1')
                        {
                            //表示私家车表中该号与其IMEI号不匹配
                            privateResult = 3;
                        }
                    }
                    else //存在该出租车 返回信息为 "Serverid:" + al[3]+"|Signature:"+al[4];
                    {
                        // type = 1 表示是出租车
                        type = 1;
                        string strSignature = result.Substring(result.IndexOf("|")+1);
                        signature = strSignature.Replace("Signature:","");
                    }

                    // type = 0 表示还未注册的私家车 或IMEI不匹配的私家车
                    if (type == 0)
                    {
                        body.Clear();
                        //body.Add(privateResult);
                        body.Add(0);
                    }
                    else
                    {

                        //---1表示出租车，3表示私家车
                        body.Add(type);
                        if (type == 1)
                        {

                            #region  AnalysisIP
                            //"Serverid:" + al[3] + "|Signature:" + al[4];
                            string strServerId = result.Substring(0, result.IndexOf('|'));
                             
                            string serverid = strServerId.Replace("Serverid:", "");
                            string serverUrl = "wh.cityofcar.com"; //数据库取
                            int svId = -1;
                            int.TryParse(serverid, out svId);
                            ServerConfigInfo serverConfig = operateDataBase.ServerConfigGetModelById(svId);
                            if (serverConfig != null)
                            {
                                serverUrl = serverConfig.DNSURL;
                            }
                    
                            #endregion
                            byte[] serverUrlbytes = Encoding.GetEncoding("GBK").GetBytes(serverUrl);
                            body.Add((byte)serverUrlbytes.Length);
                            body.AddRange(serverUrlbytes);
                        }
       
                        string phonestr = OperateConfig.GetCenterPhoneNumber();
                        byte[] phoneBcd = CommonRoutine.BcdStringToBytes(phonestr.PadLeft(12, '0'));
                        body.AddRange(phoneBcd);
                        
                        string version = "1.0";

                        //version = OperateConfig.GetTaxiClientVersion();
                        version = AcceptMainForm.TaxiClientVersion;


                        //if (type==1)
                        //{
                        //    version = OperateConfig.GetTaxiClientVersion();
                        //}
                        //else if(type==3)
                        //{
                        //    version = OperateConfig.GetPrivateCarClientVersion();
                        //}
                        byte[] vBytes = Encoding.GetEncoding("GBK").GetBytes(version);
                        body.AddRange(vBytes);
                    }
                     
                    if (type==ConstParameters.CarTypeOfTaxi)
                    {
                        DriverIdentityInfo model = operateDataBase.
                            AccreditationGetModelByPhoneNumber(driverPhoneNumber);
                        if (model!=null)
                        {
                            List<byte> msgBody = new List<byte>();
                           byte[] byteCardId = new byte[10];
                           byte[] temp = Encoding.GetEncoding("GBK").GetBytes(
                                model.IDCardNo);
                            for (int k = 0; k < byteCardId.Length; k++)
                            {
                                if (k < temp.Length)
                                {
                                    byteCardId[k] = temp[k];
                                }
                                else
                                {
                                    byteCardId[k] = 32;
                                }
                            }
                            msgBody.AddRange(byteCardId);
                            if (!string.IsNullOrEmpty(model.ServiceCardImageName))
                            {
                                msgBody.AddRange(Encoding.GetEncoding("GBK").
                                    GetBytes(model.ServiceCardImageName));
                            }
                            byte[] msgHead = OperateAgreement.GetMessageHead(
                                ConstParameters.CmdPhoneNumberExistInDbFingerPrint,
                                false, false, msgBody.Count, phoneNumberbyts,
                                serialNumber, 0, 0);
                            byte[] sendMsgData = OperateAgreement.PackageSendData(msgHead, msgBody.ToArray());
                             
                            IPEndPoint ipEndPoint = AcceptMainForm.IpEndPointList[driverPhoneNumber] as IPEndPoint;
                            AcceptMainForm.SendDataToIPAddress(sendMsgData, ipEndPoint, driverPhoneNumber);    
                                                      
                        }
                    }
        
                }

            }
            catch (Exception ex)
            {
                CommonRoutine.HandlingExceptions(ex);
                LogService.WriteLog("TaxiProtocol.cs-385");
                body.Clear();
                body.Add(0);
            }

            if (!string.IsNullOrEmpty(signature))
            {
                byte[] bybody = Encoding.GetEncoding("GBK").GetBytes(signature);
                byte[] msgHead = OperateAgreement.GetMessageHead(ConstParameters.CmdSendSignatureWhenRegist,
                                                                 false, false, bybody.Length, phoneNumberbyts,
                                                                 serialNumber, 0, 0);
                byte[] dataSig = OperateAgreement.PackageSendData(msgHead, bybody);

                IPEndPoint ipEndPoint = AcceptMainForm.IpEndPointList[driverPhoneNumber] as IPEndPoint;
                AcceptMainForm.SendDataToIPAddress(dataSig, ipEndPoint, driverPhoneNumber);
            }

            



            byte[] messageHead = OperateAgreement.GetMessageHead(ConstParameters.CmdTaxiRegisterReply3, false, false, body.Count, phoneNumberbyts,
                                                serialNumber, 0, 0);
            byte[] tempData = OperateAgreement.PackageSendData(messageHead, body.ToArray());
            return tempData;
        }


        //---------
        public byte[] TaxiRegister4(byte[] realData, IPAddress clientIp)
        {
            byte[] phoneNumberbyts = new byte[6];
            Array.Copy(realData, 5, phoneNumberbyts, 0, 6);

            byte[] serialNumber = new byte[2];
            Array.Copy(realData, 11, serialNumber, 0, 2);

            string driverPhoneNumber = OperateAgreement.GetPhoneNumInMessageHead(realData);
            //0-7  IMEI 8byte
            byte[] IMEI_bytes = new byte[8];
            Array.Copy(realData, ConstParameters.MBodySatrtIndex, IMEI_bytes, 0, 8);
            string IMEI = CommonRoutine.ByteToBcdString(IMEI_bytes);
            IMEI = IMEI.Remove(0, 1);

            //8-11  4byte  Version
            byte[] version_bytes = new byte[4];
            Array.Copy(realData, ConstParameters.MBodySatrtIndex + 8, version_bytes, 0, 4);
            Array.Reverse(version_bytes);
            int nowVersion = BitConverter.ToInt32(version_bytes, 0);

            string signature = "";

            List<byte> body = new List<byte>();
            byte cartype = 0;
            try
            {
                string result = AcceptMainForm.PositionService.TaxiRegister2(driverPhoneNumber, clientIp, IMEI, nowVersion);

                if (result == "1" || result == "2")// 1.Imei验证失败 2.未能从数据库获取到该车信息
                {
                    body.Clear();
                    body.Add(byte.Parse(result));
                }
                else
                {
                   
                    byte privateResult = 0;
                    string ss = string.Empty;
                    if (result == "0") // 该出租车号码数据库中不存在
                    {
                        string resultPrivate = AcceptMainForm.PositionService.PrivateCarRegister
                            (driverPhoneNumber, clientIp, IMEI, nowVersion);
                        if (resultPrivate[0] == '2')
                        {
                            // type = 3 表示是私家车
                            cartype = 3;
                            //"2|" + model.Signature;
                            signature = resultPrivate.Substring(
                                resultPrivate.IndexOf('|') + 1);
                        }
                        else if (resultPrivate[0] == '0')
                        {
                            //表示私家车中也无此号
                            privateResult = 0;
                        }
                        else if (resultPrivate[0] == '1')
                        {
                            //表示私家车表中该号与其IMEI号不匹配
                            privateResult = 3;
                            cartype = 3;
                        }
                    }
                    else //存在该出租车 返回信息为 "Serverid:" + al[3]+"|Signature:"+al[4];
                    {
                        // type = 1 表示是出租车
                        cartype = 1;
                        string strSignature = result.Substring(result.IndexOf("|") + 1);
                        signature = strSignature.Replace("Signature:", "");
                    }

                    // type = 0 表示还未注册的私家车 或IMEI不匹配的私家车
                    if (cartype == 0)
                    {
                        body.Clear();
                        //body.Add(privateResult);
                        body.Add(0);
                    }
                    else
                    {

                        //---1表示出租车，3表示私家车
                        body.Add(cartype);
                        if (cartype == 1)
                        {

                            #region  AnalysisIP
                            //"Serverid:" + al[3] + "|Signature:" + al[4];
                            string strServerId = result.Substring(0, result.IndexOf('|'));

                            string serverid = strServerId.Replace("Serverid:", "");
                            string serverUrl = "wh.cityofcar.com"; //数据库取
                            int svId = -1;
                            int.TryParse(serverid, out svId);
                            ServerConfigInfo serverConfig = operateDataBase.ServerConfigGetModelById(svId);
                            if (serverConfig != null)
                            {
                                serverUrl = serverConfig.DNSURL;
                            }

                            #endregion
                            byte[] serverUrlbytes = Encoding.GetEncoding("GBK").GetBytes(serverUrl);
                            body.Add((byte)serverUrlbytes.Length);
                            body.AddRange(serverUrlbytes);
                        }

                        string phonestr = OperateConfig.GetCenterPhoneNumber();
                        byte[] phoneBcd = CommonRoutine.BcdStringToBytes(phonestr.PadLeft(12, '0'));
                        body.AddRange(phoneBcd);

                        string version = "1.0";
                        if (cartype == 1)
                        {
                            //version = OperateConfig.GetTaxiClientVersion();
                            version = AcceptMainForm.TaxiClientVersion;
                        }
                        else if (cartype == 3)
                        {
                            //version = OperateConfig.GetPrivateCarClientVersion();
                            version = AcceptMainForm.PrivateCarClientVersion;
                        }
                        byte[] vBytes = Encoding.GetEncoding("GBK").GetBytes(version);
                        body.AddRange(vBytes);
                    }


                }

            }
            catch (Exception ex)
            {
                CommonRoutine.HandlingExceptions(ex);
                LogService.WriteLog("TaxiProtocol.cs-385");
                body.Clear();
                body.Add(0);
            }

           
            if (!string.IsNullOrEmpty(signature))
            {
                byte[] bybody = Encoding.GetEncoding("GBK").GetBytes(signature);
                byte[] msgHead = OperateAgreement.GetMessageHead(ConstParameters.CmdSendSignatureWhenRegist,
                                                                 false, false, bybody.Length, phoneNumberbyts,
                                                                 serialNumber, 0, 0);
                byte[] dataSig = OperateAgreement.PackageSendData(msgHead, bybody);

                IPEndPoint ipEndPoint = AcceptMainForm.IpEndPointList[driverPhoneNumber] as IPEndPoint;
                AcceptMainForm.SendDataToIPAddress(dataSig, ipEndPoint, driverPhoneNumber);
            }
             
            if (cartype==3)
            {
                PrivateCarInfo model = operateDataBase.PrivateCarGetModel(driverPhoneNumber);
                if (model!=null)
                {
                    List<byte> infobody = new List<byte>();
                    byte[] temp;
                    //TaxiNo 8byte
                    byte[] byTaxiNo= new byte[8];
                    if (model.TaxiNo == null)
                        model.TaxiNo = "";
                    temp = Encoding.GetEncoding("GBK").GetBytes(model.TaxiNo);
                    for (int k = 0; k < byTaxiNo.Length; k++)
                    {
                        if (k < temp.Length)
                        {
                            byTaxiNo[k] = temp[k];
                        }
                        else
                        {
                            byTaxiNo[k] = 32;
                        }
                    }
                    //if (!string.IsNullOrEmpty(model.TaxiNo))
                    //{
                    //    temp = Encoding.GetEncoding("GBK").GetBytes(model.TaxiNo);
                    //    Array.Copy(temp, 0, byTaxiNo, 0, temp.Length);    
                    //}                    
                    infobody.AddRange(byTaxiNo);
                    //TaxiType 24byte
                    byte[] byTaxiType = new byte[24];
                    if (model.TaxiType == null)
                        model.TaxiType = "";
                    temp = Encoding.GetEncoding("GBK").GetBytes(model.TaxiType);
                    for (int k = 0; k < byTaxiType.Length; k++)
                    {
                        if (k < temp.Length)
                        {
                            byTaxiType[k] = temp[k];
                        }
                        else
                        {
                            byTaxiType[k] = 32;
                        }
                    }

                    //if (!string.IsNullOrEmpty(model.TaxiType))
                    //{
                    //    temp = Encoding.GetEncoding("GBK").GetBytes(model.TaxiType);
                    //    Array.Copy(temp, 0, byTaxiType, 0, temp.Length);    
                    //}
                    infobody.AddRange(byTaxiType);
                    //Name -10byte
                    byte[] byName = new byte[10];
                    if (model.DriverName == null)
                        model.DriverName = "";
                    temp = Encoding.GetEncoding("GBK").GetBytes(model.DriverName);
                    for (int k = 0; k < byName.Length; k++)
                    {
                        if (k < temp.Length)
                        {
                            byName[k] = temp[k];
                        }
                        else
                        {
                            byName[k] = 32;
                        }
                    }
                    //if (!string.IsNullOrEmpty(model.DriverName))
                    //{
                    //    temp = Encoding.GetEncoding("GBK").GetBytes(model.DriverName);
                    //    Array.Copy(temp,0,byName,0,temp.Length);
                    //}
                    infobody.AddRange(byName);
                    //Gender 1byte
                    infobody.Add(model.DriverGender);

                    byte[] msgHead = OperateAgreement.GetMessageHead(
                        ConstParameters.CmdSendPrivateCarInfoWhenRegist,
                        false, false, infobody.Count, phoneNumberbyts,
                        serialNumber, 0, 0);
                    byte[] infoData = OperateAgreement.PackageSendData(msgHead, infobody.ToArray());

                    IPEndPoint ipEndPoint = AcceptMainForm.IpEndPointList[driverPhoneNumber] as IPEndPoint;
                    AcceptMainForm.SendDataToIPAddress(infoData, ipEndPoint, driverPhoneNumber);

                }
            }
           

            byte[] messageHead = OperateAgreement.GetMessageHead(ConstParameters.CmdPrivateCarRegisterReply, false, false, body.Count, phoneNumberbyts,
                                                serialNumber, 0, 0);
            byte[] tempData = OperateAgreement.PackageSendData(messageHead, body.ToArray());
            return tempData;
        }







        public byte[] PrivateRegistRequest(byte[] realData)
        {
            byte[] phoneNumberbyts = new byte[6];
            Array.Copy(realData, 5, phoneNumberbyts, 0, 6);
             byte[] serialNumber = new byte[2];
            Array.Copy(realData, 11, serialNumber, 0, 2);

            string phoneNumber = OperateAgreement.GetPhoneNumInMessageHead(realData);
            Random ram = new Random();
            int intRandom = ram.Next(0, 999999);         
            string strRandom =  intRandom.ToString("000000");
            AcceptMainForm.PrivateCarRegistCodeList[phoneNumber] =
            strRandom+"|"+DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");


           

            //发短信phoneNumber 
            string smsContent = "感谢您注册智能电召平台,您的验证码为【";
            smsContent += intRandom.ToString("000000");
            smsContent += "】,请在限定时间内在软件中输入该验证码。";
            string result = UnicomSMS.SendSMS(phoneNumber, smsContent);
            byte resultByte = 0;
            if (result.Contains("发送短信成功"))
            {
                resultByte = 1;
            }
            byte body = resultByte;
            byte[] head = OperateAgreement.GetMessageHead(
                ConstParameters.CmdPrivateCarRegistRequestReply,
                false, false, 1, phoneNumberbyts, serialNumber, 0, 0);
            List<byte> message = new List<byte>();
            message.AddRange(head);
            message.Add(body);
            return message.ToArray();
        }


        public byte[] PrivateCarVerifyRegistCode(byte[] realData)
        {
            byte[] phoneNumberbyts = new byte[6];
            Array.Copy(realData, 5, phoneNumberbyts, 0, 6);
             byte[] serialNumber = new byte[2];
            Array.Copy(realData, 11, serialNumber, 0, 2);

            string phoneNumber = OperateAgreement.GetPhoneNumInMessageHead(realData);
            //0-7  IMEI 8byte
            byte[] IMEI_bytes = new byte[8];
            Array.Copy(realData, ConstParameters.MBodySatrtIndex, IMEI_bytes, 0, 8);
            string IMEI = CommonRoutine.ByteToBcdString(IMEI_bytes);
            IMEI = IMEI.Remove(0, 1);

            //从消息体中取出验证码 8-10
            byte[] registCodeBytes = new byte[3];
            Array.Copy(realData,ConstParameters.MBodySatrtIndex+8,registCodeBytes,0,3);            
            string registcode = CommonRoutine.ByteToBcdString(registCodeBytes);
          
            List<byte> body = new List<byte>();
            if (operateDataBase.ExistsDriverPhoneNumber(phoneNumber) != null)
            {
                body.Add(7);//该号码已被出租车使用
            }
            else
            {
                if (AcceptMainForm.PrivateCarRegistCodeList.Contains(phoneNumber) ||
                        registcode == DateTime.Now.AddDays(1).ToString("yyMMdd")
                        || registcode == "010203")
                {
                    string[] verifyInfo = null ;
                    if (AcceptMainForm.PrivateCarRegistCodeList.Contains(phoneNumber))
                    {
                        string value = AcceptMainForm.PrivateCarRegistCodeList
                        [phoneNumber].ToString();
                        verifyInfo = value.Split('|');
                    }
                   
                    if ( (verifyInfo!=null && verifyInfo[0] == registcode)
                        || registcode == DateTime.Now.AddDays(1).ToString("yyMMdd")
                        ||registcode=="010203")
                    {
                        TimeSpan span = new TimeSpan();
                        if (verifyInfo!=null)
                        {
                            span= DateTime.Now - DateTime.Parse(verifyInfo[1]);                                            
                        }

                        if (verifyInfo!=null && span.Seconds > 100)
                        {                             
                            body.Add(2);    //表示验证码正确但已超时                                                  
                        }
                        else//验证成功
                        {
                            PrivateCarInfo model = new PrivateCarInfo();
                            model.PhoneNumber = phoneNumber;
                            model.IMEI = IMEI;
                            model.RegistTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                            model.LastLoginTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                            //=======记录手机号和Imei 注册时间====
                            //判断该号码是否注册过 
                            if (operateDataBase.PrivateCarExistsPhoneNum(phoneNumber))
                            {
                                //注册过 则删除先前的记录 添加新记录
                                if (operateDataBase.PrivateCarDeleteByPhoneNum(phoneNumber))
                                {
                                    if (operateDataBase.PrivateCarAdd(model))
                                    {
                                        body.Add(1); //表示注册成功  可尝试登录    
                                    }
                                    else
                                    {
                                        body.Add(3);//表示添加到数据库时发生错误
                                    }
                                }
                                else
                                {
                                    body.Add(6);//该手机号以前注册过，数据库删除先前记录时发生错误
                                }
                            }
                            else
                            {
                                if (operateDataBase.PrivateCarAdd(model))
                                {
                                    body.Add(1); //表示注册成功  可尝试登录    
                                }
                                else
                                {
                                    body.Add(3);//表示添加到数据库时发生错误
                                }
                            }

                        }
                    }
                    else
                    {
                        body.Add(4);//表示验证码错误
                    }
                }
                else
                {
                    body.Add(5);//表示该号码未请求过注册
                }
            }
           

            byte[] messageHead = OperateAgreement.GetMessageHead(
                ConstParameters.CmdPrivateCarVerifyRegistCodeReply, false, false, body.Count, new byte[6], 
                                            new byte[2], 0, 0);
            byte[] tempData = OperateAgreement.PackageSendData(messageHead, body.ToArray());
            return tempData;            
        }

         
        //private string  RegisterByDataBase(string phoneNumber, IPAddress ip, string IMEI, int version)
        //{
        //    // taxiId、driverName、readIMEI、Serverid
        //    ArrayList al = operateDataBase.ExistsDriverPhoneNumber(phoneNumber);

        //    if (al != null)
        //    {
        //        string readIMEI = al[2].ToString();
        //        if (string.IsNullOrEmpty(readIMEI))
        //        {
        //            //set IMEI 到数据库
        //            //更新到数据库
        //            if (operateDataBase.UpdateIMEIByPhoneNumber(phoneNumber, IMEI))
        //            {
        //                Console.WriteLine("IMEI更新成功！");
        //            }
        //            else
        //            {
        //                Console.WriteLine("IMEI更新失败！");
        //            }
        //        }
        //        else
        //        {
        //            if (readIMEI != IMEI && IMEI != "")
        //            { return "1"; }//IMEI 验证失败
        //        }

        //        int taxiId = Convert.ToInt32(al[0]);
        //        string driverName = al[1].ToString();
        //        //--id-TaxiNo-TaxiType -Remark
        //        TaxiInfo taxiInfo = operateDataBase.DriverGetModel(taxiId);
        //        if (taxiInfo != null)
        //        {
        //            taxiInfo.DriverPhoneNumber = phoneNumber;
        //            taxiInfo.DriverName = driverName;
        //            taxiInfo.Ip = ip;
        //            taxiInfo.IsCalling = 0;
        //            taxiInfo.StartLevel = operateDataBase.GetDriverStar(phoneNumber);
        //            taxiInfo.Version = version;

        //            AcceptMainForm.RentCarList[phoneNumber] = taxiInfo;
        //           // PositionMainForm.TaxiList[phoneNumber] = taxiInfo;

        //            return "Serverid:" + al[3];
        //        }
        //        else
        //        {
        //            return "2";
        //        }
        //    }
        //    else
        //    {
        //        return "0"; //表示数据库没这个号码
        //    }

        //}


        public byte[] TaxiQueryAd(byte[] realData)
        {
            byte[] phoneNumberbyts = new byte[6];
            Array.Copy(realData, 5, phoneNumberbyts, 0, 6);
            byte[] serialNumber = new byte[2];
            Array.Copy(realData, 11, serialNumber, 0, 2);

            string phoneNumber = OperateAgreement.GetPhoneNumInMessageHead(realData);
            DataSet ds = operateDataBase.TaxiGetAdSeting(phoneNumber);
            List<byte> sendListBytes = new List<byte>();


            if (ds != null && ds.Tables.Count > 0)
            {
                List<byte> mDelbodyList = new List<byte> { 0 };
                mDelbodyList.AddRange(Encoding.GetEncoding("GBK").GetBytes("FF00Q0099好"));
                byte[] mDelbody = mDelbodyList.ToArray();
                byte[] mDelHead = OperateAgreement.GetMessageHead(ConstParameters.CmdTaxiQueryAdReply, false, false, mDelbody.Length, phoneNumberbyts,
                                                    serialNumber, 0, 0);
                byte[] tempData = OperateAgreement.PackageSendData(mDelHead, mDelbody);

                sendListBytes.AddRange(tempData);
                foreach (DataRow dr in ds.Tables[0].Rows)
                {
                    List<byte> mbody = new List<byte>() { 1 };
                    string adid = dr["adid"].ToString();
                    string adContent = dr["ADContent"].ToString();
                    string adRollSpeed = dr["adRollSpeed"].ToString();
                    string adEffect = dr["ADEffect"].ToString();
                    string adStaytime = dr["AdStaytime"].ToString();
                    for (int i = 1; i < 5; i++)
                    {
                        string[] ss = dr["Stime" + i].ToString().Split(':');
                        string[] ee = dr["Etime" + i].ToString().Split(':');
                        mbody.AddRange(ss.Select(temp => byte.Parse(temp)));
                        mbody.AddRange(ee.Select(temp => byte.Parse(temp)));
                    }
                    if (int.Parse(adid) < 10) { adid = "0" + adid; }
                    if (int.Parse(adEffect) == 10) { adEffect = "A"; }
                    string strcmd = GetSetTaxiAdStrCmd(adid, adEffect, adRollSpeed, adStaytime, adContent);
                    mbody.AddRange(Encoding.GetEncoding("GBK").GetBytes(strcmd));


                    byte[] mbodydata = mbody.ToArray();
                    byte[] mHead = OperateAgreement.GetMessageHead(ConstParameters.CmdTaxiQueryAdReply, false, false, mbodydata.Length, phoneNumberbyts,
                                                        serialNumber, 0, 0);
                    byte[] tempData1 = OperateAgreement.PackageSendData(mHead, mbodydata);

                    sendListBytes.AddRange(tempData1);
                }
            }
            return sendListBytes.ToArray();
        }

        public string GetSetTaxiAdStrCmd(string number, string adEffects, string speed, string statTime, string adcontent)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("FF");  // LED Address  (2L)
            sb.Append(number); //AD serial number (2L)
            sb.Append(adEffects);// AD Effects (1L)
            sb.Append(speed); // 1L
            sb.Append(statTime); //1L
            sb.Append(1);
            sb.Append(adcontent);

            return sb.ToString();
        }

        public byte[] TaxiQueryArea(byte[] realData)
        {
            byte[] phoneNumberbyts = new byte[6];
            Array.Copy(realData, 5, phoneNumberbyts, 0, 6);
            byte[] serialNumber = new byte[2];
            Array.Copy(realData, 11, serialNumber, 0, 2);
            string phoneNumber = OperateAgreement.GetPhoneNumInMessageHead(realData);

            DataSet ds = operateDataBase.TaxiGetAreaSeting(phoneNumber);
            List<byte> sendListBytes = new List<byte>();


            if (ds != null && ds.Tables.Count > 0)
            {
                foreach (DataRow dr in ds.Tables[0].Rows)
                {
                    List<byte> mbody = new List<byte>();
                    double leftLat = double.Parse(dr["LeftLat"].ToString());
                    double leftLon = double.Parse(dr["LeftLon"].ToString());
                    double rightLat = double.Parse(dr["rightLat"].ToString());
                    double rightLon = double.Parse(dr["rightLon"].ToString());

                    //leftLat 5
                    string leftLatstr = ((int)(leftLat * Math.Pow(10, 6))).ToString(CultureInfo.InvariantCulture).PadLeft(10, '0');
                    mbody.AddRange(CommonRoutine.BcdStringToBytes(leftLatstr));

                    //leftLon 5
                    string leftLonstr = ((int)(leftLon * Math.Pow(10, 6))).ToString(CultureInfo.InvariantCulture).PadLeft(10, '0');
                    mbody.AddRange(CommonRoutine.BcdStringToBytes(leftLonstr));

                    //rightLat 5
                    string rightLatstr = ((int)(rightLat * Math.Pow(10, 6))).ToString(CultureInfo.InvariantCulture).PadLeft(10, '0');
                    mbody.AddRange(CommonRoutine.BcdStringToBytes(rightLatstr));

                    //rightLon 5
                    string rightLonstr = ((int)(rightLon * Math.Pow(10, 6))).ToString(CultureInfo.InvariantCulture).PadLeft(10, '0');
                    mbody.AddRange(CommonRoutine.BcdStringToBytes(rightLonstr));


                    string[] ss = dr["Stime"].ToString().Split(':');
                    string[] ee = dr["Etime"].ToString().Split(':');
                    mbody.AddRange(ss.Select(byte.Parse));
                    mbody.AddRange(ee.Select(byte.Parse));

                    byte[] mbodydata = mbody.ToArray();
                    byte[] mHead = OperateAgreement.GetMessageHead(ConstParameters.CmdTaxiQueryAreaReply, false, false, mbodydata.Length, phoneNumberbyts,
                                      serialNumber, 0, 0);
                    byte[] tempData1 = OperateAgreement.PackageSendData(mHead, mbodydata);

                    sendListBytes.AddRange(tempData1);
                }
                if (ds.Tables[0].Rows.Count == 0)
                {
                    byte[] tempData1 = OperateAgreement.GetEmptyBodyMessageData(ConstParameters.CmdTaxiQueryAreaReply);
                    sendListBytes.AddRange(tempData1);
                }
            }
            else
            {
                byte[] tempData1 = OperateAgreement.GetEmptyBodyMessageData(ConstParameters.CmdTaxiQueryAreaReply);
                sendListBytes.AddRange(tempData1);
            }

            return sendListBytes.ToArray();
        }



        //UpdataTaxiCallingState
        public byte[] UpdataTaxiCallingState(byte[] realData)
        {
            string phoneNumber = OperateAgreement.GetPhoneNumInMessageHead(realData);
            AcceptMainForm.PositionService.UpdateTaxiCallingState(phoneNumber, realData[ConstParameters.MBodySatrtIndex]);
            switch (realData[ConstParameters.MBodySatrtIndex])
            {
                case 1:
                    CallRecordsInfo model = new CallRecordsInfo();
                    model.PhoneNumber = phoneNumber;
                    model.CallTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                    model.Type = 3;
                    operateDataBase.CallRecordAdd(model);
                    break;
                case 2:
                    CallRecordsInfo model2 = new CallRecordsInfo();
                    model2.PhoneNumber = phoneNumber;
                    model2.CallTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                    model2.Type = 4;
                    operateDataBase.CallRecordAdd(model2);
                    break;
            }
            return OperateAgreement.GetEmptyBodyMessageData(ConstParameters.CmdTaxiIsCallingReply);
        }

        public byte[] UpdataTaxiWarningInfo(byte[] realData)
        {

            string phoneNumber = OperateAgreement.GetPhoneNumInMessageHead(realData);
            byte warningState = realData[ConstParameters.MBodySatrtIndex];
            string state = OperateAgreement.GetTaxiWarmingState(warningState);
            TaxiWarmingInfo model = new TaxiWarmingInfo();
            model.Datetime = DateTime.Now;
            model.PhoneNumber = phoneNumber;
            model.WarmingState = state;
            if (operateDataBase.TaxiWarmingAdd(model))
            {
                Console.WriteLine("出租车报警记录添加成功：" + phoneNumber + DateTime.Now);
            }
            else
            {
                Console.WriteLine("出租车报警记录添加失败：" + phoneNumber + DateTime.Now);
            }

            return OperateAgreement.GetEmptyBodyMessageData(ConstParameters.CmdTaxiUpdataWarningInfoRely);
        }

        public byte[] GetWarningConfig(byte[] realData)
        {
            string phonenumber = OperateAgreement.GetPhoneNumInMessageHead(realData);



            byte[] mbodydata = new byte[3];
            mbodydata[0] = 20; //剩余电量
            mbodydata[1] = 70; //超速
            mbodydata[2] = 12; //超时停车    *10分钟

            string[] parameters = operateDataBase.GetWarmingParmsByPhoneNumber(phonenumber);
            if (parameters != null)
            {
                int speedOut = int.Parse(parameters[0]);
                int stopTimeOut = int.Parse(parameters[1]);
                int powerLeft = int.Parse(parameters[2]);
                mbodydata[0] = (byte)powerLeft;
                mbodydata[1] = (byte)speedOut;
                mbodydata[2] = (byte)stopTimeOut;
            }

            byte[] mHead = OperateAgreement.GetMessageHead(ConstParameters.CmdTaxiGetWarningConfigReply, false, false, mbodydata.Length, new byte[6],
                              new byte[2], 0, 0);
            byte[] tempData1 = OperateAgreement.PackageSendData(mHead, mbodydata);
            return tempData1;

        }

        public byte[] GetTaxiNo(byte[] realData)
        {
            byte[] phoneNumberbyts = new byte[6];
            Array.Copy(realData, 5, phoneNumberbyts, 0, 6);

            byte[] serialNumber = new byte[2];
            Array.Copy(realData, 11, serialNumber, 0, 2);

            string driverPhoneNumber = OperateAgreement.GetPhoneNumInMessageHead(realData);
            string taxino = operateDataBase.GetTaxiNoByPhoneNumber(driverPhoneNumber);

            List<byte> messageBody = new List<byte>();
            byte[] taxiNobytes = new byte[8];
            byte[] tempTaxiNobytes = Encoding.GetEncoding("GBK").GetBytes(taxino);
            for (int k = 0; k < taxiNobytes.Length; k++)
            {
                if (k < tempTaxiNobytes.Length)
                {
                    taxiNobytes[k] = tempTaxiNobytes[k];
                }
                else
                {
                    taxiNobytes[k] = 32;
                }
            }
            messageBody.AddRange(taxiNobytes);

            byte[] messageHead = OperateAgreement.GetMessageHead(ConstParameters.CmdTaxiGetTaxiNoReply,
                false, false, messageBody.Count, phoneNumberbyts, serialNumber, 0, 0);
            byte[] tempData = OperateAgreement.PackageSendData(messageHead, messageBody.ToArray());
            return tempData;
        }

        public byte[] GetBlackList(byte[] realData)
        {
            byte[] phoneNumberbyts = new byte[6];
            Array.Copy(realData, 5, phoneNumberbyts, 0, 6);

            byte[] serialNumber = new byte[2];
            Array.Copy(realData, 11, serialNumber, 0, 2);

            List<string> blackList = operateDataBase.GetBlackListOfPasseager();

            List<byte> messageBody = new List<byte>();
            foreach (string blackPhone in blackList)
            {
                byte[] bytePhone = CommonRoutine.BcdStringToBytes(blackPhone);
                messageBody.AddRange(bytePhone);
            }

            byte[] messageHead = OperateAgreement.GetMessageHead(ConstParameters.CmdTaxiGetBlackListReply,
                false, false, messageBody.Count, phoneNumberbyts, serialNumber, 0, 0);
            byte[] tempData = OperateAgreement.PackageSendData(messageHead, messageBody.ToArray());
            return tempData;
        }

        public byte[] SetSignature(byte[] realData)
        {
            byte[] phoneNumberbyts = new byte[6];
            Array.Copy(realData, 5, phoneNumberbyts, 0, 6);
              string phoneNumber = OperateAgreement.GetPhoneNumInMessageHead(realData);
            byte[] serialNumber = new byte[2];
            Array.Copy(realData, 11, serialNumber, 0, 2);

            byte carType = realData[ConstParameters.MBodySatrtIndex];           
            string strSignature = Encoding.GetEncoding("GBK").GetString(
                realData,ConstParameters.MBodySatrtIndex+1,
                realData.Length-ConstParameters.MhLenth-1);
            bool dbResult = false;
            switch (carType)
            {
                case ConstParameters.CarTypeOfTaxi:
                    dbResult = operateDataBase.TaxiUpdateSignature(phoneNumber, strSignature);
                    break;
                case ConstParameters.CarTypeOfRent:
                    break;
                case ConstParameters.CarTypeOfPrivate:
                    dbResult = operateDataBase.PrivateCarUpdateSignature(phoneNumber, strSignature);
                    break;
            }
            byte[] head = OperateAgreement.GetMessageHead(
                ConstParameters.CmdCarSetSignatureReply, false, false,
                1, phoneNumberbyts, serialNumber, 0, 0);
            //List<byte> message = new List<byte>();
            //message.AddRange(head);        
            //message.Add((byte) (dbResult ? 1:0));
             
            //if (dbResult)
            //{
            //   bool bl = AcceptMainForm.PositionService.UpdateCarSignature(
            //       phoneNumber, strSignature);
            //}
            //return message.ToArray();

            if (dbResult)
            {
                bool bl = AcceptMainForm.PositionService.UpdateCarSignature(
                  phoneNumber, strSignature);
            }
            
            byte[] tempData = OperateAgreement.PackageSendData(head,
                new byte[1] { (byte)(dbResult ? 1 : 0) });
            return tempData;

        }

        public byte[] PrivateCarUpdateInfos(byte[] realData)
        {
            byte[] phoneNumberbyts = new byte[6];
            Array.Copy(realData, 5, phoneNumberbyts, 0, 6);
            string phoneNumber = OperateAgreement.GetPhoneNumInMessageHead(realData);
            byte[] serialNumber = new byte[2];
            Array.Copy(realData, 11, serialNumber, 0, 2);
            // TaxiNO - 8byte
            byte[] byteTaxiNo = new byte[8];
            Array.Copy(realData, ConstParameters.MBodySatrtIndex, byteTaxiNo, 0, 8);
            string strTaxiNO = Encoding.GetEncoding("GBK").GetString(byteTaxiNo).Replace("\0","");
            // TaxiType -24byte
            byte[] byteTaxiType = new byte[24];
            Array.Copy(realData, ConstParameters.MBodySatrtIndex+8, 
                byteTaxiType, 0, 24);
            string strTaxiType = Encoding.GetEncoding("GBK").GetString(byteTaxiType).Replace("\0", ""); ;
            // DriverName -10byte
            byte[] byteDriverName = new byte[10];
            Array.Copy(realData, ConstParameters.MBodySatrtIndex + 32, 
                byteDriverName, 0, 10);
            string strDriverName = Encoding.GetEncoding("GBK").GetString(byteDriverName).Replace("\0", ""); ;
            byte driverGender = realData[ConstParameters.MBodySatrtIndex + 42];

            PrivateCarInfo model = new PrivateCarInfo();
            model.PhoneNumber = phoneNumber;
            model.TaxiNo = strTaxiNO;
            model.TaxiType = strTaxiType;
            model.DriverName = strDriverName;
            model.DriverGender = driverGender;

            bool result = operateDataBase.PrivateCarUpdateInfoByPhoneNumber(model);

            byte[] head = OperateAgreement.GetMessageHead(
                ConstParameters.CmdPrivateCarSetInfosReply, false, false,
                1, phoneNumberbyts, serialNumber, 0, 0);
            List<byte> message = new List<byte>();
            message.AddRange(head);
            //message.Add((byte)(result ? 1 : 0));
            //return message.ToArray();
            byte[] body = new byte[1];
            body[0] = (byte) (result ? 1 : 0);
            if (result)
            {
                bool bl = AcceptMainForm.PositionService.UpdatePrivateCarInfosInMemory(model);
            }
 
            byte[] tempData = OperateAgreement.PackageSendData(head,body);
            return tempData;
             
        }


        public byte[] GetVersionByCarType(byte[] realData)
        {
            byte[] phoneNumberbyts = new byte[6];
            Array.Copy(realData, 5, phoneNumberbyts, 0, 6);
          //  string phoneNumber = OperateAgreement.GetPhoneNumInMessageHead(realData);
            byte[] serialNumber = new byte[2];
            Array.Copy(realData, 11, serialNumber, 0, 2);

            byte carType = realData[ConstParameters.MBodySatrtIndex];
            string strversion = "0";
            switch (carType)
            {
                case ConstParameters.CarTypeOfPrivate:
                    //strversion = OperateConfig.GetPrivateCarClientVersion();
                    strversion = AcceptMainForm.PrivateCarClientVersion;
                    break;
                case ConstParameters.CarTypeOfTaxi:
                    //strversion = OperateConfig.GetTaxiClientVersion();
                    strversion = AcceptMainForm.TaxiClientVersion;
                    break;
            }
            int version = 0;
            int.TryParse(strversion,out version);


            byte[] head = OperateAgreement.GetMessageHead(
              ConstParameters.CmdGetCarClientVersionReply, false, false,4
              , phoneNumberbyts, serialNumber, 0, 0);
            List<byte> message = new List<byte>();
            message.AddRange(head);
                       
            byte[] body = BitConverter.GetBytes(version);
            Array.Reverse(body);

            byte[] tempData = OperateAgreement.PackageSendData(head, body);
            return tempData;
            
        }

             //---------
        public byte[] SpecialCarRegister(byte[] realData, IPAddress clientIp)
        {
            byte[] phoneNumberbyts = new byte[6];
            Array.Copy(realData, 5, phoneNumberbyts, 0, 6);

            byte[] serialNumber = new byte[2];
            Array.Copy(realData, 11, serialNumber, 0, 2);

            string phoneNumber = OperateAgreement.GetPhoneNumInMessageHead(realData);
            //0-7  IMEI 8byte
            byte[] IMEI_bytes = new byte[8];
            Array.Copy(realData, ConstParameters.MBodySatrtIndex, IMEI_bytes, 0, 8);
            string imei = CommonRoutine.ByteToBcdString(IMEI_bytes);
            imei = imei.Remove(0, 1);

            //8-11  4byte  Version
            byte[] version_bytes = new byte[4];
            Array.Copy(realData, ConstParameters.MBodySatrtIndex + 8, version_bytes, 0, 4);
            Array.Reverse(version_bytes);
            int nowVersion = BitConverter.ToInt32(version_bytes, 0);

            string result = AcceptMainForm.PositionService.SpecialCarRegister(
                phoneNumber, clientIp, imei, nowVersion);
            List<byte> body = new List<byte>();
            if (result=="0"||result=="1")
            {
                int intResult = int.Parse(result);
                body.Add((byte)intResult);
            }
            else if (result.StartsWith("2|"))
            {
                //0：2，1：type,2:serverId,3:signature
                string[] infos = result.Split('|');
               
                // cartype -1byte
                int carType = int.Parse(infos[1]);
                body.Add((byte)carType);

                string serverUrl = "wh.cityofcar.com";  
                ServerConfigInfo serverConfig =
                operateDataBase.ServerConfigGetModelById(int.Parse(infos[2]));        
                if (serverConfig != null)
                {
                    serverUrl = serverConfig.DNSURL;
                }                     
                byte[] serverUrlbytes = Encoding.GetEncoding("GBK").GetBytes(serverUrl);
                // url-length  1-byte
                body.Add((byte)serverUrlbytes.Length);
                //url - bytes
                body.AddRange(serverUrlbytes);
                string version = "1.0";
                version = AcceptMainForm.SpecialCarClientVersion;                 
                byte[] vBytes = Encoding.GetEncoding("GBK").GetBytes(version);
                //version - bytes    
                body.AddRange(vBytes);                 
            }

            byte[] messageHead = OperateAgreement.GetMessageHead(
                ConstParameters.CmdSpecialCarRegistReply, false, false, 
                body.Count, phoneNumberbyts,serialNumber, 0, 0);
            byte[] tempData = OperateAgreement.PackageSendData(messageHead, body.ToArray());
            return tempData;
            
        }

        public byte[] PlatformLogin(byte[] realData, IPAddress clientIp)
        {
            byte[] phoneNumberbyts = new byte[6];
            Array.Copy(realData, 5, phoneNumberbyts, 0, 6);

            byte[] serialNumber = new byte[2];
            Array.Copy(realData, 11, serialNumber, 0, 2);

            string phoneNumber = OperateAgreement.GetPhoneNumInMessageHead(realData);
           
            //0-3  4byte  Version
            byte[] version_bytes = new byte[4];
            Array.Copy(realData, ConstParameters.MBodySatrtIndex, version_bytes, 0, 4);
            Array.Reverse(version_bytes);
            int nowVersion = BitConverter.ToInt32(version_bytes, 0);

            if (operateDataBase.PhonePlatformExistsNumber(phoneNumber))
            {
               bool bl = operateDataBase.PhonePlatformUpdateAfterLogin(
                   phoneNumber, nowVersion.ToString());
            }
            else
            {
                PhonePlatformInfo model = new PhonePlatformInfo();
                model.Number = phoneNumber;
                model.FirstLoginTime = DateTime.Now;
                model.LastLoginTime = DateTime.Now;
                model.LoginCount = 1;
                model.Version = nowVersion.ToString();
                bool bl = operateDataBase.PhonePlatformAdd(model);
            }
             
            List<byte> body = new List<byte>();


            //version - 4 bytes    
            int version = AcceptMainForm.PhonePlatformVersion;
            byte[] vBytes = BitConverter.GetBytes(version);
            Array.Reverse(vBytes);            
            body.AddRange(vBytes);
            

            byte[] messageHead = OperateAgreement.GetMessageHead(
                ConstParameters.CmdPhonePlatformLoginReply, false, false,
                body.Count, phoneNumberbyts, serialNumber, 0, 0);
            byte[] tempData = OperateAgreement.PackageSendData(messageHead, body.ToArray());
            return tempData;

        }

        public byte[] PlatformUpdateArea(byte[] realData)
        {
            byte[] phoneNumberbyts = new byte[6];
            Array.Copy(realData, 5, phoneNumberbyts, 0, 6);

            byte[] serialNumber = new byte[2];
            Array.Copy(realData, 11, serialNumber, 0, 2);

            string phoneNumber = OperateAgreement.GetPhoneNumInMessageHead(realData);

            int bodyLength = OperateAgreement.GetMessageLengthInMessageHead(realData);

            string strArea = ASCIIEncoding.GetEncoding("GBK").GetString(
                realData, ConstParameters.MBodySatrtIndex, bodyLength);

            bool result = operateDataBase.PhonePlatformUpdateArea(phoneNumber, strArea);
            int  intResult = result ? 1 : 0;

            List<byte> body = new List<byte>();             
            body.Add((byte)intResult);
             
            byte[] messageHead = OperateAgreement.GetMessageHead(
                ConstParameters.CmdPhonePlatformUpdateAreaReply, false, false,
                body.Count, phoneNumberbyts, serialNumber, 0, 0);
            byte[] tempData = OperateAgreement.PackageSendData(messageHead, body.ToArray());
            return tempData;

        }

        
        public byte[] CheckIdentity(byte[] realData)
        {
            byte[] phoneNumberbyts = new byte[6];
            Array.Copy(realData, 5, phoneNumberbyts, 0, 6);

            byte[] serialNumber = new byte[2];
            Array.Copy(realData, 11, serialNumber, 0, 2);

            string phoneNumber = OperateAgreement.GetPhoneNumInMessageHead(realData);
             
            string strId = ASCIIEncoding.GetEncoding("GBK").GetString(
                realData, ConstParameters.MBodySatrtIndex,10).Trim('\0');
            string strPwd = ASCIIEncoding.GetEncoding("GBK").GetString(
                realData, ConstParameters.MBodySatrtIndex+10, 10).Trim('\0');

            byte btResult = 0;

            DriverIdentityInfo model = operateDataBase.AccreditationCheckIdentityWithReturn(
                strId, strPwd);
          
            if (model!=null)
            {
                btResult = 1;
            }
            //此处需将该记录加如数据库中
            CardCheckHistoryInfo cardCheck = new CardCheckHistoryInfo();
            cardCheck.CardId = strId;
            cardCheck.CheckResult = btResult.ToString();
            cardCheck.PhoneNumber = phoneNumber;
            cardCheck.CheckTime = DateTime.Now;
            bool addHistory = operateDataBase.CardCheckHistoryAdd(cardCheck);


            List<byte> body = new List<byte>();
            body.Add((byte)btResult);
            if (model!=null&&!string.IsNullOrEmpty(model.ServiceCardImageName))
            {
                body.AddRange(Encoding.GetEncoding("GBK").GetBytes(model.ServiceCardImageName));
            }
            byte[] messageHead = OperateAgreement.GetMessageHead(
                ConstParameters.CmdTaxiCheckIdentityReply, false, false,
                body.Count, phoneNumberbyts, serialNumber, 0, 0);
            byte[] tempData = OperateAgreement.PackageSendData(messageHead, body.ToArray());
            return tempData;

        }

        public byte[] ChangePasswordOfIdCard(byte[] realData)
        {
            byte[] phoneNumberbyts = new byte[6];
            Array.Copy(realData, 5, phoneNumberbyts, 0, 6);

            byte[] serialNumber = new byte[2];
            Array.Copy(realData, 11, serialNumber, 0, 2);

            string phoneNumber = OperateAgreement.GetPhoneNumInMessageHead(realData);

            string strId = ASCIIEncoding.GetEncoding("GBK").GetString(
                realData, ConstParameters.MBodySatrtIndex, 10).Trim('\0');
            string strOldPwd = ASCIIEncoding.GetEncoding("GBK").GetString(
                realData, ConstParameters.MBodySatrtIndex + 10, 10).Trim('\0');

            string strNewPwd = ASCIIEncoding.GetEncoding("GBK").GetString(
              realData, ConstParameters.MBodySatrtIndex + 20, 10).Trim('\0');

            byte btResult = 0;
            bool result = operateDataBase.AccreditationChangePassword(
                strId, strOldPwd,strNewPwd);//-1 为数据库错误，0为验证失败，大于0表示通过
            if (result)
            {
                btResult = 1;
            }
              
            List<byte> body = new List<byte>();
            body.Add((byte)btResult);

            byte[] messageHead = OperateAgreement.GetMessageHead(
                ConstParameters.CmdTaxiChangePasswordOfIdCardReply, false, false,
                body.Count, phoneNumberbyts, serialNumber, 0, 0);
            byte[] tempData = OperateAgreement.PackageSendData(messageHead, body.ToArray());
            return tempData;

        }


        public void CdmaTaxiUpdataGpsInfo(byte[] realData, IPAddress clientIp)
        {
            
            byte mainPowerByte = realData[realData.Length - 3];// 30或31
            byte stateByte = realData[realData.Length - 2];
            string strState = Convert.ToString(stateByte, 2).PadLeft(8, '0');
            strState = strState.Substring(4, 4);

            //strState[3] ACC_PIN   
            //strState[2] EMPTY_LAMP_PIN       0为空载  1载客
            //strState[1] DAY_NIGHT_PIN        0为白班 1为夜班  
            //strState[0] SERVICE_PIN          0为服务  1为暂停 
            string[] dataInfo = Encoding.ASCII.GetString(realData).Split('-');
            if (dataInfo.Length!=11)
            {
                Console.WriteLine("Cdma data array length is not value 11....");
                return;
            }
            TaxiCdmaInfo model = null;
            bool isLogin;
            string deviceNumber = dataInfo[0].Replace("*", "");
            if (!AcceptMainForm.CdmaTaxiList.Contains(dataInfo[0].Replace("*","")))
            {
                //新登录设备
                isLogin = true;
                model = operateDataBase.CdmaTaxiGetModelByDeviceNumber(deviceNumber);
                if (model==null)
                {
                    Console.WriteLine("CdmaTaxiUpdataGpsInfo : 未找到设备-"+deviceNumber);
                    return;
                }
            }
            else
            {
                isLogin = false;
                model = AcceptMainForm.CdmaTaxiList[deviceNumber] as TaxiCdmaInfo;
                if (model==null)
                {
                    return;
                }
            }
            string strLat = dataInfo[4];
            string strLng = dataInfo[6];
            double lat = 0;
            double lng = 0;
            if (strLat != "" && strLat.Contains(".") && strLng != "" && strLng.Contains("."))
            {
                string strIntLat = strLat.Remove(strLat.IndexOf(".") - 2);
                string strLeftLat = strLat.Substring(strLat.IndexOf(".") - 2);
                float fLeftLat = float.Parse(strLeftLat)/60;
                int intLat = int.Parse(strIntLat);
                lat = (double)intLat + fLeftLat;

                string strIntLng = strLng.Remove(strLng.IndexOf(".")-2);
                string strLeftLng = strLng.Substring(strLng.IndexOf(".") - 2);
                float fLeftLng = float.Parse(strLeftLng) / 60;
                int intLng = int.Parse(strIntLng);
                lng = (double)intLng + fLeftLng;

            }
            double newLat = 0;
            double newLng = 0; 
            CommonRoutine.TransformWGSToGCJ(lat, lng, out newLat, out newLng);
           
            TaxiGpsHistoryInfo taxiGpsHistoryInfo = new TaxiGpsHistoryInfo();
            taxiGpsHistoryInfo.Longitude = double.Parse(newLng.ToString("f6"));// double.Parse(dataInfo[6]) / 100;
            taxiGpsHistoryInfo.Latitude = double.Parse(newLat.ToString("f6"));//double.Parse(dataInfo[4]) / 100;
            taxiGpsHistoryInfo.Taxistate = 0x00;
            taxiGpsHistoryInfo.Taxistate = strState[1] == '0' ? (byte)0x00 : (byte)0x02;

            //strState[3] ACC_PIN   
            //strState[2] EMPTY_LAMP_PIN       0为白班 1为夜班  
            //strState[1] DAY_NIGHT_PIN        0为空载  1载客   
            //strState[0] SERVICE_PIN          0为服务  1为暂停 


            if (strState[0] == '1')//暂停服务
            {
                taxiGpsHistoryInfo.Taxistate = (byte)0x02;
            }
           
            if (strState[2]=='0')//0为白班
            {
                taxiGpsHistoryInfo.DriverPhoneNumber = model.PhoneNumberDay;
                if (model.CurrentDriver.ToString()!="0" || isLogin)//白夜班状态改变 更新位置服务器
                {
                    if (model.PhoneNumberDay != model.PhoneNumberNight)
                    {
                        AcceptMainForm.PositionService.RemoveCdmaTaxi(model.PhoneNumberNight);
                    }                    
                    model.CurrentDriver = 0;
                }
               
            }
            else
            {
                taxiGpsHistoryInfo.DriverPhoneNumber = model.PhoneNumberNight;
                if (model.CurrentDriver.ToString() != "1" || isLogin)//白夜班状态改变 更新位置服务器
                {
                    if (model.PhoneNumberDay != model.PhoneNumberNight)
                    {
                        AcceptMainForm.PositionService.RemoveCdmaTaxi(model.PhoneNumberDay);
                    }                            
                    model.CurrentDriver = 1;
                }                
            }             
            // taxiGpsHistoryInfo.AlarmL = realData[ConstParameters.MBodySatrtIndex + 11];     
            model.UpdateTime = DateTime.Now;
            AcceptMainForm.CdmaTaxiList[deviceNumber] = model;

            taxiGpsHistoryInfo.Time = DateTime.Now;
            float fSpeed = 0;
            float fAngle = 0;
            float.TryParse(dataInfo[8], out fSpeed);
            float.TryParse(dataInfo[9], out fAngle); 
            #region

            TaxiInfo taxiInfo = new TaxiInfo
            {
                DriverPhoneNumber = taxiGpsHistoryInfo.DriverPhoneNumber,
                UpdateTime = taxiGpsHistoryInfo.Time,
                TaxiState = taxiGpsHistoryInfo.Taxistate,
                Latitude = taxiGpsHistoryInfo.Latitude,
                Longitude = taxiGpsHistoryInfo.Longitude,
                Ip = clientIp,
                AlarmL = taxiGpsHistoryInfo.AlarmL,
                Angle = (short)fAngle,
                Speed = (byte)fSpeed,
                CarDeviceType = 1,
                StartLevel =5
            };              
            try
            { 
                AcceptMainForm.PositionService.UpdateTaxiInfo(taxiInfo);
                // lock (AcceptMainForm.TaxiGpsHistoryInfoQueue) 
                {
                    AcceptMainForm.DataQueue.Enqueue(taxiGpsHistoryInfo);
                }
            }
            catch (Exception ex)
            {
                CommonRoutine.HandlingExceptions(ex);
                LogService.WriteLog("TaxiProtocol.cs-111");
            }

            #endregion

        }

    }
}
